import { app, BrowserWindow, shell } from "electron";
import { join } from "node:path";
import { ICON, DIST, preload, url } from "../main/utils";

const NODE_ENV = process.env.NODE_ENV;
const indexHtml = join(DIST, "./index.html");
let mainWindow: BrowserWindow | null;

// 主窗口
const createWindow = (): BrowserWindow => {
  //动态适应宽高
  // const { width, height } = screen.getPrimaryDisplay().workAreaSize;
  // 创建浏览器窗口
  mainWindow = new BrowserWindow({
    title: "pear-rec",
    icon: ICON,
    width: 1000,
    height: 750,
    frame: false,
    show: false,
    webPreferences: {
      preload,
    },
  });

  mainWindow.setMenu(null); // 去掉顶部菜单

  if (url) {
    mainWindow.loadURL(url);
    mainWindow.webContents.openDevTools();
  } else {
    mainWindow.loadFile(indexHtml);
  }

  mainWindow.on("closed", () => {
    mainWindow = null;
  });
  mainWindow.on("ready-to-show", () => {
    showMainWin();
  });

  return mainWindow;
};

// 关闭窗口
function closeMainWin() {
  if (mainWindow?.isDestroyed()) {
    mainWindow!.close();
  }
  mainWindow = null;
}

// 打开窗口
function openMainWin() {
  mainWindow = createWindow();
  mainWindow!.show();
}

// 显示窗口
function showMainWin() {
  if (!mainWindow || mainWindow?.isDestroyed()) {
    mainWindow = createWindow();
  }
  mainWindow!.show();
}

// 隐藏窗口
function hideMainWin() {
  mainWindow!.hide();
}

// 最小化窗口
function minimizeMainWin() {
  mainWindow!.minimize();
}

// 最大化窗口
function maximizeMainWin() {
  mainWindow!.maximize();
}

// 取消最大化窗口
function unmaximizeMainWin() {
  mainWindow!.unmaximize();
}

// 是否最大化
function isMaximized() {
  return mainWindow!.isMaximized();
}

function focusMainWin() {
  if (mainWindow) {
    // Focus on the main window if the user tried to open another
    if (mainWindow.isMinimized()) mainWindow.restore();
    mainWindow.focus();
  }
}

export {
  mainWindow,
  createWindow,
  closeMainWin,
  openMainWin,
  hideMainWin,
  showMainWin,
  focusMainWin,
  minimizeMainWin,
  isMaximized,
  maximizeMainWin,
  unmaximizeMainWin,
};
